<script lang="ts">
import Vue from 'vue'
import navBar from "@/components/nav-bar/nav-bar.vue";
import my_form_item from "@/components/my_form_item/index.vue";
import {mapState} from "vuex";
import tips from "@/utils/tips";
import {getCanPaper, getFileExtension} from "@/utils/utils";
import my_upload_card from "@/components/my_upload_card/index.vue";
import PayCard from "@/components/PayCard/PayCard.vue";
import {createOrder, getTaskId} from "@/services/order";

export default Vue.extend({
  name: "photo_pay",
  components: {PayCard, my_upload_card, my_form_item, navBar},
  data() {
    return {
      nums: 1,
      printColor: false, // 彩色
      isDoubleSided: false, // 双面
      type: 1, // 打印什么 1 照片, 2:证件
      totalPrice: 0,
      currentImage: '', // 单个照片 (证件)
      currentImageList: [],

      radioCurrent: '1', //打印方向
      radioEdge: '2', // 双面分类
      paperSize: '9', // 打印纸

      showUpload: false,
      uploadProgress: 0,
    }
  },
  computed: {
    ...mapState(["machine", "printer", "machineOnline"]),
    lang(): any {
      return this.$t('print_pay');
    }
  },
  onLoad(options) {
    const type = parseInt(options.type)
    this.type = type;
    const currentImage = JSON.parse(decodeURIComponent(options.image));
    if (type === 1) {
      this.currentImage = currentImage
    } else if (type === 2) { // 多个照片
      this.currentImageList = currentImage
    }
    console.log('currentImageList', this.currentImageList)
    this.calculatePrice()
  },
  methods: {
    getCanPaper,
    // 预览
    openPreview(tempFilePath: any) {
      uni.previewImage({
        current: 1,
        urls: [tempFilePath]
      })
    },
    // 删除照片
    closeImage(index: Number) {
      if (this.currentImageList.length >= 1) {
        this.currentImageList.splice(index, 1)
      }
      this.calculatePrice();
    },

    // 选择纸
    onPaperType(event: any) {
      const {value} = event.detail
      this.paperSize = value
      this.radioEdge = value === '8' ? '3' : '2'
      this.calculatePrice();
    },

    // 添加和却掉 打印数量
    onNums(event: any) {
      this.nums = event.value
      this.calculatePrice();
    },

    // 双面点击事
    onDouble(e: any) {
      console.log("this.radioCurrent", this.radioCurrent)
      this.isDoubleSided = e.target.value;
      this.calculatePrice();
    },

    // 双面 长边 或 短边
    onRadioEdgeChange(e: any) {
      this.radioEdge = e.detail.value;
    },

    // 彩色打印点击
    onPrintColor(e: any) {
      this.printColor = e.target.value;
      this.calculatePrice();
    },

    // 打印方向 radio Group
    onOrientationRadioGroup(event: any) {
      const {value} = event.detail
      this.radioCurrent = value
      if (this.paperSize === '9') {
        this.radioEdge = value === '1' ? '2' : '3'
      }
      console.log("this.radioCurrent", this.radioCurrent)
    },


    // 计算价格
    calculatePrice() {
      const {nums, type, printColor, isDoubleSided: double, paperSize, printer, currentImageList} = this;
      console.log(":double  =--", double)
      // Get prices based on paper type (A3/A4)
      const getPrices = (size: string) => {
        const prefix = size.toLowerCase();
        return {
          single: {
            black: parseFloat(printer[`${prefix}_image_black_white_price`]),
            color: parseFloat(printer[`${prefix}_image_color_price`])
          },
          double: {
            black: parseFloat(printer[`${prefix}_double_image_black_white_price`]),
            color: parseFloat(printer[`${prefix}_double_image_color_price`])
          }
        };
      };

      if (type === 1) { // ID Document
        const prices = getPrices('a4');
        this.totalPrice = nums * prices.single.black;
      } else if (type === 2) { // Photos
        let totalPages = currentImageList.length;
        console.log("totalPages -=-=", totalPages)
        // if (double) {
        //   totalPages = totalPages === 1 ? totalPages : Math.ceil(totalPages / 2);
        // }
        const totalCopies = totalPages * nums;
        console.log("totalPages ", totalCopies)
        // 根据纸张类型(A3/A4)获取对应价格
        const prices = getPrices(parseInt(paperSize) === 9 ? 'a4' : 'a3');
        console.log("prices =--=", prices)
        console.log("double =--=", double)
        const unitPrice = prices[double ? 'double' : 'single'][printColor ? 'color' : 'black'];
        console.log("unitPrice =--=", unitPrice)

        this.totalPrice = double ? (totalCopies / 2) * unitPrice : totalCopies * unitPrice;
      }
    },


    // 计算价格
    // calculatePrice() {
    //   // a3_double_image_black_white_price: "1.60"
    //   // a3_double_image_color_price: "2.30"
    //   // a3_double_side_price: "0.00"
    //   // a3_image_black_white_price: "1.30"
    //   // a3_image_color_price: "2.00"
    //   // a4_image_color_price: "1.00"
    //   // a4_image_black_white_price: "0.60"
    //   // a4_double_image_color_price: "1.50"
    //   // a4_double_image_black_white_price: "1.20"
    //
    //   const nums = this.nums
    //   const type = this.type // 证据按还是照片 0 证件 1 照片
    //   const printColor = this.printColor
    //   const isDoubleSided = this.isDoubleSided
    //   const paperSize = parseFloat(this.paperSize) // 打印纸 类型
    //   const a4_image_color_price = parseFloat(this.printer.a4_image_color_price);
    //   const a4_image_black_white_price = parseFloat(this.printer.a4_image_black_white_price);
    //   const a4_double_image_color_price = parseFloat(this.printer.a4_double_image_color_price);
    //   const a4_double_image_black_white_price = parseFloat(this.printer.a4_double_image_black_white_price);
    //
    //   let price = 0
    //   let totalPage = 0
    //
    //   if (type === 1) { // 证件
    //     price = nums * a4_image_black_white_price
    //   } else if (type === 2) { // 照片
    //     totalPage = this.currentImageList.length
    //     totalPage = totalPage * nums
    //
    //     if (paperSize === 9) { // A4
    //       if (!printColor && !isDoubleSided) { // 什么都没有选择
    //         price = totalPage * a4_image_black_white_price
    //       } else if (!isDoubleSided && printColor) { // 彩色
    //         price = totalPage * a4_image_color_price
    //       } else if (!printColor && isDoubleSided) { // 双面
    //         totalPage = totalPage === 1 ? totalPage : Math.ceil(totalPage / 2)
    //         price = totalPage * a4_double_image_black_white_price
    //       } else if (isDoubleSided && printColor) { // 双面 和 彩色
    //         totalPage = totalPage === 1 ? totalPage : Math.ceil(totalPage / 2)
    //         price = totalPage * a4_double_image_color_price
    //       }
    //     } else { // 选择了 A3
    //       const a3_color_price = parseFloat(this.printer.a3_image_color_price);
    //       const a3_black_white_price = parseFloat(this.printer.a3_image_black_white_price);
    //       const a3_double_color_price = parseFloat(this.printer.a3_double_image_color_price);
    //       const a3_double_black_white_price = parseFloat(this.printer.a3_double_image_black_white_price);
    //       if (printColor && isDoubleSided) {
    //         totalPage = totalPage === 1 ? totalPage : Math.ceil(totalPage / 2)
    //         price = totalPage * a3_double_color_price;
    //       } else if (!printColor && isDoubleSided) {
    //         totalPage = totalPage === 1 ? totalPage : Math.ceil(totalPage / 2)
    //         price = totalPage * a3_double_black_white_price;
    //       } else if (printColor && !isDoubleSided) {
    //         price = totalPage * a3_color_price;
    //       } else if (!printColor && !isDoubleSided) {
    //         price = totalPage * a3_black_white_price;
    //       }
    //     }
    //   }
    //
    //   this.totalPrice = price.toFixed(2)
    //   console.log('totalPrice========该付款的价格', this.totalPrice)
    // },

    // 支付
    async printPay() {
      // 检查盒子状态
      if (!this.machineOnline) {
        tips.toast(this.otherLang.not_printer);
        this.$store.commit("setMachineOnline");
        return;
      }

      const {
        type, currentImage, currentImageList, nums, isDoubleSided, printColor, paperSize, radioCurrent, radioEdge,
        printer: {id, port, driver_name}, machine: {device_id, device_password}
      } = this

      let page = 0;
      let ext = '';
      let jobFile = '';
      if (type === 1) { // 证件
        page = 1
        jobFile = currentImage;
        ext = getFileExtension(currentImage)
      } else if (type === 2) { // 照片
        page = currentImageList.length
        jobFile = currentImageList.join('\n');
        ext = getFileExtension(currentImageList[0])
      }

      const printParams: any = {
        deviceId: device_id, //  盒子ID
        deviceKey: device_password, // 盒子密码
        devicePort: port, // 盒子端口
        printerModel: driver_name, // 打印机型号
        dmCopies: nums, // 打印份数
        dmPaperSize: parseInt(paperSize), // 纸张类型
        isPreview: 0, // 预览
        dmDefaultSource: 7,
        jpAutoScale: 4, // 自动缩放
        jpScale: 'fit', // 缩放
        jpAutoAlign: 'z5', // 自动对齐
        pdfKernel: 'mode1', // 文字增强
        jpPageRange: '',
        ext, // 打印文件扩展名
        page,// 页码
        jobFile, // 打印文件
        jpAutoRotate: 0, // 自动旋转
        reportDeviceStatus: 1, // 拦截设备状态异常任务
        reportPrinterStatus: 1, // 拦截打印机状态异常任务
        dmColor: printColor ? 2 : 1, // 打印颜色
        dmOrientation: parseInt(radioCurrent), // 打印方向
        dmDuplex: isDoubleSided ? parseInt(radioEdge) : 1, // 双面打印
      };

      uni.showLoading({title: '加载中...'});
      try {
        const result = await createOrder({
          printer_id: id, params: printParams, type: 'image', files: [printParams.jobFile]
        });

        console.log("准备支付=====", result);
        if (result.code === 200) {
          const {wechat_order, order_id} = result.data;
          await uni.requestPayment({
            ...wechat_order,
            success: async () => {
              tips.toast("支付成功")
              const tackIdRes = await getTaskId(order_id);
              const {code, data: {task_id}, msg} = tackIdRes;
              if (code === 200) {
                console.log("printFileFun-=--=-=-=- task_id", order_id, task_id)
                // 为了预览
                printParams.taskId = task_id
                await uni.navigateTo({
                  url: `/pages/print_loading/print_loading?params=${
                      encodeURIComponent(JSON.stringify({order_id, type, print_params: printParams}))}`
                });
              } else {
                tips.toast(msg, 6000);
                console.log("printFileFun-=--=-=-=-", tackIdRes)
              }
            },
            fail: (err) => {
              console.log('支付失败:', err);
            },
          });
        } else {
          console.log('创建订单失败:', result);
          tips.toast(result.msg);
        }
      } catch (err) {
        console.error('创建订单失败:', err);
      } finally {
        uni.hideLoading();
      }
    },
  }
})
</script>

<template>
  <view>
    <nav-bar :page-title="lang.page_name"/>

    <view :class="locale" style="padding: 30rpx 30rpx 100rpx 30rpx">
      <view class="flex-column" style="font-size:28rpx;gap: 18rpx">

        <!-- 最上面的 查看或删除照片-->
        <view class="flex-between radio-20 padding-14-20 bg-white" style="min-height: 202rpx;">
          <view class="flex-center padding-20 wrap gap-20">

            <view v-if="type !== 1 && currentImageList.length > 0" v-for="(item, index) in currentImageList"
                  :key="index" @click="openPreview(item)" style="position: relative">
              <view v-if="currentImageList.length > 1" class="close-icon" @click="closeImage(index)">
                <u-icon size="26px" color="#0009" name="close-circle-fill"/>
              </view>
              <view class="column-center radio-20 photo-box">
                <image class="photo" :src="item" :style="{filter: printColor ? 'grayscale(0)' : ''}"/>
              </view>
            </view>

            <!-- 证件 -->
            <view v-if="type === 1 && currentImage" class="column-center radio-20 photo-box"
                  @click="openPreview(currentImage)">
              <image class="photo" :src="currentImage"/>
            </view>
          </view>
        </view>

        <!-- 选择打印纸-->
        <my_form_item :label="lang.paper_type">
          <template #left_content>
            <radio-group @change="onPaperType" v-model="paperSize" class="flex-center text-32 gap-30">
              <!-- A3-->
              <label for="A3" class="flex-center gap-8"> {{ lang.a3 }}
                <radio id="A3" :disabled="!(getCanPaper(printer.paper_types_supported, 'A3') && type !== 1)"
                       color="#07c160"
                       value="8" class="transform-nine"/>
              </label>
              <!-- A4-->
              <label for="A4" class="flex-center gap-8"> {{ lang.a4 }}
                <radio id="A4" checked color="#07c160" value="9" class="transform-nine"/>
              </label>
            </radio-group>
          </template>
        </my_form_item>

        <!-- 选择打印数量-->
        <my_form_item :label="lang.printNums">
          <template #left_content>
            <u-number-box v-model="nums" @change="onNums" :min="1" :max="50" integer/>
          </template>
        </my_form_item>

        <!--      双面打印 不是证件的话 和 打印机能打印双面的话-->
        <my_form_item v-if="type !== 1 && printer.supports_double_side === 1 && currentImageList.length >= 2"
                      :label="lang.double_print">
          <template #left_content>
            <view class="flex-center gap-8">
              <switch @change="onDouble" color="#07c160"/>
            </view>
          </template>
        </my_form_item>

        <!--      双面分类-->
        <my_form_item v-if="isDoubleSided" :label="lang.double_type">
          <template #left_content>
            <radio-group @change="onRadioEdgeChange" v-model="radioEdge" class="flex-center text-32 gap-30">
              <!-- 短边 -->
              <label for="shortEdge" class="flex-center gap-8"> {{ lang.short_edge }}
                <radio id="shortEdge" :checked="radioEdge==='3'" color="#07c160" value="3" class="transform-nine"/>
              </label>
              <!-- 长边-->
              <label for="longEdge" class="flex-center gap-8"> {{ lang.long_edge }}
                <radio id="longEdge" :checked="radioEdge==='2'" color="#07c160" value="2" class="transform-nine"/>
              </label>
            </radio-group>
          </template>
        </my_form_item>

        <!-- 彩色打印  不是证件的话 和 打印机能打印彩色的话-->
        <my_form_item v-if="type !== 1 && printer.supports_color === 1" :label="lang.print_color">
          <template #left_content>
            <view class="flex-center gap-8">
              <switch @change="onPrintColor" :checked="printColor" color="#07c160"/>
            </view>
          </template>
        </my_form_item>

        <!-- 打印方向-->
        <my_form_item v-if="type !== 1" :label="lang.orientation">
          <template #left_content>
            <radio-group @change="onOrientationRadioGroup" v-model="radioCurrent" class="flex-center text-32 gap-30">
              <!-- 横向 -->
              <label for="horizontal" class="flex-center gap-8"> {{ lang.horizontal }}
                <radio id="horizontal" color="#07c160" value="2" class="transform-nine"/>
              </label>
              <!-- 竖向-->
              <label for="vertical" class="flex-center gap-8"> {{ lang.vertical }}
                <radio id="vertical" checked color="#07c160" value="1" class="transform-nine"/>
              </label>
            </radio-group>
          </template>
        </my_form_item>
      </view>

      <pay-card :pay-price="totalPrice" @on-pay="printPay"/>
      <!-- 上传中-->
      <my_upload_card :upload-progress="uploadProgress" :upload-name="otherLang.image" :show="showUpload"/>
    </view>
  </view>
</template>

<style scoped lang="scss">
.photo-box {
  width: 140rpx;
  position: relative;
  border: 2rpx dashed #1073FF;

  .photo {
    width: 134rpx;
    height: 134rpx;
    filter: grayscale(1);
  }
}


.close-icon {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  z-index: 99;
}
</style>